[[...path]].page.tsx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. import type { ReactNode, JSX } from 'react';
  2. import React, { useEffect } from 'react';
  3. import EventEmitter from 'events';
  4. import { isIPageInfo } from '@growi/core';
  5. import type {
  6. IDataWithMeta, IPageInfo, IPagePopulatedToShowRevision,
  7. } from '@growi/core';
  8. import {
  9. isClient, pagePathUtils, pathUtils,
  10. } from '@growi/core/dist/utils';
  11. import ExtensibleCustomError from 'extensible-custom-error';
  12. import type {
  13. GetServerSideProps, GetServerSidePropsContext,
  14. } from 'next';
  15. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  16. import dynamic from 'next/dynamic';
  17. import Head from 'next/head';
  18. import { useRouter } from 'next/router';
  19. import superjson from 'superjson';
  20. import { BasicLayout } from '~/components/Layout/BasicLayout';
  21. import { PageView } from '~/components/PageView/PageView';
  22. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  23. import { SupportedAction, type SupportedActionType } from '~/interfaces/activity';
  24. import type { CrowiRequest } from '~/interfaces/crowi-request';
  25. import { RegistrationMode } from '~/interfaces/registration-mode';
  26. import type { RendererConfig } from '~/interfaces/services/renderer';
  27. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  28. import type { CurrentPageYjsData } from '~/interfaces/yjs';
  29. import type { PageModel, PageDocument } from '~/server/models/page';
  30. import type { PageRedirectModel } from '~/server/models/page-redirect';
  31. import { useEditorModeClassName } from '~/services/layout/use-editor-mode-class-name';
  32. import {
  33. useCurrentUser,
  34. useIsForbidden, useIsSharedUser,
  35. useIsEnabledStaleNotification, useIsIdenticalPath,
  36. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  37. useDefaultIndentSize, useIsIndentSizeForced,
  38. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  39. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  40. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  41. useIsAllReplyShown, useShowPageSideAuthors, useIsContainerFluid, useIsNotCreatable,
  42. useIsUploadAllFileAllowed, useIsUploadEnabled, useIsBulkExportPagesEnabled,
  43. useElasticsearchMaxBodyLengthToIndex,
  44. useIsLocalAccountRegistrationEnabled,
  45. useIsRomUserAllowedToComment,
  46. useIsPdfBulkExportEnabled,
  47. useIsAiEnabled, useLimitLearnablePageCountPerAssistant, useIsUsersHomepageDeletionEnabled,
  48. } from '~/stores-universal/context';
  49. import { useEditingMarkdown } from '~/stores/editor';
  50. import {
  51. useSWRxCurrentPage, useSWRMUTxCurrentPage, useCurrentPageId,
  52. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  53. } from '~/stores/page';
  54. import { useRedirectFrom } from '~/stores/page-redirect';
  55. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  56. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  57. import { useCurrentPageYjsData, useSWRMUTxCurrentPageYjsData } from '~/stores/yjs';
  58. import loggerFactory from '~/utils/logger';
  59. import type { NextPageWithLayout } from './_app.page';
  60. import type { CommonProps } from './utils/commons';
  61. import {
  62. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR, addActivity,
  63. } from './utils/commons';
  64. declare global {
  65. // eslint-disable-next-line vars-on-top, no-var
  66. var globalEmitter: EventEmitter;
  67. }
  68. const GrowiContextualSubNavigationSubstance = dynamic(() => import('~/client/components/Navbar/GrowiContextualSubNavigation'), { ssr: false });
  69. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  70. const DisplaySwitcher = dynamic(() => import('~/client/components/Page/DisplaySwitcher').then(mod => mod.DisplaySwitcher), { ssr: false });
  71. const PageStatusAlert = dynamic(() => import('~/client/components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  72. const UnsavedAlertDialog = dynamic(() => import('~/client/components/UnsavedAlertDialog'), { ssr: false });
  73. const DescendantsPageListModal = dynamic(
  74. () => import('~/client/components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal),
  75. { ssr: false },
  76. );
  77. const DrawioModal = dynamic(() => import('~/client/components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  78. const HandsontableModal = dynamic(() => import('~/client/components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  79. const TemplateModal = dynamic(() => import('~/client/components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  80. const LinkEditModal = dynamic(() => import('~/client/components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  81. const TagEditModal = dynamic(() => import('~/client/components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  82. const ConflictDiffModal = dynamic(() => import('~/client/components/PageEditor/ConflictDiffModal').then(mod => mod.ConflictDiffModal), { ssr: false });
  83. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  84. const EditablePageEffects = dynamic(() => import('~/client/components/Page/EditablePageEffects').then(mod => mod.EditablePageEffects), { ssr: false });
  85. const logger = loggerFactory('growi:pages:all');
  86. const {
  87. isPermalink: _isPermalink, isCreatablePage,
  88. } = pagePathUtils;
  89. const { removeHeadingSlash } = pathUtils;
  90. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfo>;
  91. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  92. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  93. {
  94. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  95. return v?.data != null
  96. && v?.data.toObject != null
  97. && isIPageInfo(v.meta);
  98. },
  99. serialize: (v) => {
  100. return {
  101. data: superjson.stringify(v.data.toObject()),
  102. meta: superjson.stringify(v.meta),
  103. };
  104. },
  105. deserialize: (v) => {
  106. return {
  107. data: superjson.parse(v.data),
  108. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  109. };
  110. },
  111. },
  112. 'IPageToShowRevisionWithMetaTransformer',
  113. );
  114. // GrowiContextualSubNavigation for NOT shared page
  115. type GrowiContextualSubNavigationProps = {
  116. isLinkSharingDisabled: boolean,
  117. }
  118. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  119. const { isLinkSharingDisabled } = props;
  120. const { data: currentPage } = useSWRxCurrentPage();
  121. return (
  122. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  123. );
  124. };
  125. type Props = CommonProps & {
  126. pageWithMeta: IPageToShowRevisionWithMeta | null,
  127. // pageUser?: any,
  128. redirectFrom?: string;
  129. // shareLinkId?: string;
  130. isLatestRevision?: boolean,
  131. isIdenticalPathPage?: boolean,
  132. isForbidden: boolean,
  133. isNotFound: boolean,
  134. isNotCreatable: boolean,
  135. // isAbleToDeleteCompletely: boolean,
  136. templateTagData?: string[],
  137. templateBodyData?: string,
  138. isLocalAccountRegistrationEnabled: boolean,
  139. isSearchServiceConfigured: boolean,
  140. isSearchServiceReachable: boolean,
  141. isSearchScopeChildrenAsDefault: boolean,
  142. elasticsearchMaxBodyLengthToIndex: number,
  143. isEnabledMarp: boolean,
  144. isRomUserAllowedToComment: boolean,
  145. sidebarConfig: ISidebarConfig,
  146. isSlackConfigured: boolean,
  147. // isMailerSetup: boolean,
  148. isAclEnabled: boolean,
  149. // hasSlackConfig: boolean,
  150. drawioUri: string | null,
  151. // highlightJsStyle: string,
  152. isAllReplyShown: boolean,
  153. showPageSideAuthors: boolean,
  154. isContainerFluid: boolean,
  155. isUploadEnabled: boolean,
  156. isUploadAllFileAllowed: boolean,
  157. isBulkExportPagesEnabled: boolean,
  158. isPdfBulkExportEnabled: boolean,
  159. isEnabledStaleNotification: boolean,
  160. isEnabledAttachTitleHeader: boolean,
  161. // isEnabledLinebreaks: boolean,
  162. // isEnabledLinebreaksInComments: boolean,
  163. adminPreferredIndentSize: number,
  164. isIndentSizeForced: boolean,
  165. disableLinkSharing: boolean,
  166. skipSSR: boolean,
  167. ssrMaxRevisionBodyLength: number,
  168. yjsData: CurrentPageYjsData,
  169. rendererConfig: RendererConfig,
  170. aiEnabled: boolean,
  171. limitLearnablePageCountPerAssistant: number,
  172. isUsersHomepageDeletionEnabled: boolean,
  173. };
  174. const Page: NextPageWithLayout<Props> = (props: Props) => {
  175. // register global EventEmitter
  176. if (isClient() && window.globalEmitter == null) {
  177. window.globalEmitter = new EventEmitter();
  178. }
  179. const router = useRouter();
  180. useCurrentUser(props.currentUser ?? null);
  181. // commons
  182. useCsrfToken(props.csrfToken);
  183. useGrowiCloudUri(props.growiCloudUri);
  184. // page
  185. useIsContainerFluid(props.isContainerFluid);
  186. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  187. useIsForbidden(props.isForbidden);
  188. useIsNotCreatable(props.isNotCreatable);
  189. useRedirectFrom(props.redirectFrom ?? null);
  190. useIsSharedUser(false); // this page cann't be routed for '/share'
  191. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  192. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  193. useIsSearchPage(false);
  194. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  195. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  196. useIsSearchServiceReachable(props.isSearchServiceReachable);
  197. useElasticsearchMaxBodyLengthToIndex(props.elasticsearchMaxBodyLengthToIndex);
  198. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  199. useIsSlackConfigured(props.isSlackConfigured);
  200. // useIsMailerSetup(props.isMailerSetup);
  201. useIsAclEnabled(props.isAclEnabled);
  202. // useHasSlackConfig(props.hasSlackConfig);
  203. useDefaultIndentSize(props.adminPreferredIndentSize);
  204. useIsIndentSizeForced(props.isIndentSizeForced);
  205. useDisableLinkSharing(props.disableLinkSharing);
  206. useRendererConfig(props.rendererConfig);
  207. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  208. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  209. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  210. useIsAllReplyShown(props.isAllReplyShown);
  211. useShowPageSideAuthors(props.showPageSideAuthors);
  212. useIsUploadAllFileAllowed(props.isUploadAllFileAllowed);
  213. useIsUploadEnabled(props.isUploadEnabled);
  214. useIsBulkExportPagesEnabled(props.isBulkExportPagesEnabled);
  215. useIsPdfBulkExportEnabled(props.isPdfBulkExportEnabled);
  216. useIsLocalAccountRegistrationEnabled(props.isLocalAccountRegistrationEnabled);
  217. useIsRomUserAllowedToComment(props.isRomUserAllowedToComment);
  218. useIsAiEnabled(props.aiEnabled);
  219. useLimitLearnablePageCountPerAssistant(props.limitLearnablePageCountPerAssistant);
  220. useIsUsersHomepageDeletionEnabled(props.isUsersHomepageDeletionEnabled);
  221. const { pageWithMeta } = props;
  222. const pageId = pageWithMeta?.data._id;
  223. const revisionId = pageWithMeta?.data.revision?._id;
  224. const revisionBody = pageWithMeta?.data.revision?.body;
  225. useCurrentPathname(props.currentPathname);
  226. const { data: currentPage } = useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  227. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  228. const { trigger: mutateCurrentPageYjsDataFromApi } = useSWRMUTxCurrentPageYjsData();
  229. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  230. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  231. const { mutate: mutateIsNotFound } = useIsNotFound();
  232. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  233. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  234. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  235. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  236. const { mutate: mutateCurrentPageYjsData } = useCurrentPageYjsData();
  237. useSetupGlobalSocket();
  238. useSetupGlobalSocketForPage(pageId);
  239. // Store initial data (When revisionBody is not SSR)
  240. useEffect(() => {
  241. if (!props.skipSSR) {
  242. return;
  243. }
  244. if (currentPageId != null && revisionId != null && !props.isNotFound) {
  245. const mutatePageData = async() => {
  246. const pageData = await mutateCurrentPage();
  247. mutateEditingMarkdown(pageData?.revision?.body);
  248. };
  249. // If skipSSR is true, use the API to retrieve page data.
  250. // Because pageWIthMeta does not contain revision.body
  251. mutatePageData();
  252. }
  253. }, [
  254. revisionId, currentPageId, mutateCurrentPage,
  255. mutateCurrentPageYjsDataFromApi, mutateEditingMarkdown, props.isNotFound, props.skipSSR,
  256. ]);
  257. // Load current yjs data
  258. useEffect(() => {
  259. if (currentPageId != null && revisionId != null && !props.isNotFound) {
  260. mutateCurrentPageYjsDataFromApi();
  261. }
  262. }, [currentPageId, mutateCurrentPageYjsDataFromApi, props.isNotFound, revisionId]);
  263. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  264. useEffect(() => {
  265. const decodedURI = decodeURI(window.location.pathname);
  266. if (isClient() && decodedURI !== props.currentPathname) {
  267. const { search, hash } = window.location;
  268. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  269. }
  270. }, [props.currentPathname, router]);
  271. // initialize mutateEditingMarkdown only once per page
  272. // need to include useCurrentPathname not useCurrentPagePath
  273. useEffect(() => {
  274. if (props.currentPathname != null) {
  275. mutateEditingMarkdown(revisionBody);
  276. }
  277. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  278. useEffect(() => {
  279. mutateRemoteRevisionId(revisionId);
  280. }, [mutateRemoteRevisionId, revisionId]);
  281. useEffect(() => {
  282. mutateCurrentPageId(pageId ?? null);
  283. }, [mutateCurrentPageId, pageId]);
  284. useEffect(() => {
  285. mutateIsNotFound(props.isNotFound);
  286. }, [mutateIsNotFound, props.isNotFound]);
  287. useEffect(() => {
  288. mutateIsLatestRevision(props.isLatestRevision);
  289. }, [mutateIsLatestRevision, props.isLatestRevision]);
  290. useEffect(() => {
  291. mutateTemplateTagData(props.templateTagData);
  292. }, [props.templateTagData, mutateTemplateTagData]);
  293. useEffect(() => {
  294. mutateTemplateBodyData(props.templateBodyData);
  295. }, [props.templateBodyData, mutateTemplateBodyData]);
  296. useEffect(() => {
  297. mutateCurrentPageYjsData(props.yjsData);
  298. }, [mutateCurrentPageYjsData, props.yjsData]);
  299. // If the data on the page changes without router.push, pageWithMeta remains old because getServerSideProps() is not executed
  300. // So preferentially take page data from useSWRxCurrentPage
  301. const pagePath = currentPage?.path ?? pageWithMeta?.data.path ?? props.currentPathname;
  302. const title = generateCustomTitleForPage(props, pagePath);
  303. return (
  304. <>
  305. <Head>
  306. <title>{title}</title>
  307. </Head>
  308. <div className="dynamic-layout-root justify-content-between">
  309. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  310. <PageView
  311. className="d-edit-none"
  312. pagePath={pagePath}
  313. initialPage={pageWithMeta?.data}
  314. rendererConfig={props.rendererConfig}
  315. />
  316. <EditablePageEffects />
  317. <DisplaySwitcher />
  318. <PageStatusAlert />
  319. </div>
  320. </>
  321. );
  322. };
  323. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  324. const editorModeClassName = useEditorModeClassName();
  325. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  326. };
  327. type LayoutProps = Props & {
  328. children?: ReactNode
  329. }
  330. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  331. // init sidebar config with UserUISettings and sidebarConfig
  332. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  333. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  334. };
  335. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  336. return (
  337. <>
  338. <GrowiPluginsActivator />
  339. <DrawioViewerScript drawioUri={page.props.rendererConfig.drawioUri} />
  340. <Layout {...page.props}>
  341. {page}
  342. </Layout>
  343. <UnsavedAlertDialog />
  344. <DescendantsPageListModal />
  345. <DrawioModal />
  346. <HandsontableModal />
  347. <QuestionnaireModalManager />
  348. <TemplateModal />
  349. <LinkEditModal />
  350. <TagEditModal />
  351. <ConflictDiffModal />
  352. </>
  353. );
  354. };
  355. function getPageIdFromPathname(currentPathname: string): string | null {
  356. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  357. }
  358. class MultiplePagesHitsError extends ExtensibleCustomError {
  359. pagePath: string;
  360. constructor(pagePath: string) {
  361. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  362. this.pagePath = pagePath;
  363. }
  364. }
  365. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  366. const { model: mongooseModel } = await import('mongoose');
  367. const req: CrowiRequest = context.req as CrowiRequest;
  368. const { crowi } = req;
  369. const { revisionId } = req.query;
  370. const Page = crowi.model('Page') as PageModel;
  371. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  372. const { pageService, configManager } = crowi;
  373. let currentPathname = props.currentPathname;
  374. const pageId = getPageIdFromPathname(currentPathname);
  375. const isPermalink = _isPermalink(currentPathname);
  376. const { user } = req;
  377. if (!isPermalink) {
  378. // check redirects
  379. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  380. if (chains != null) {
  381. // overwrite currentPathname
  382. currentPathname = chains.end.toPath;
  383. props.currentPathname = currentPathname;
  384. // set redirectFrom
  385. props.redirectFrom = chains.start.fromPath;
  386. }
  387. // check whether the specified page path hits to multiple pages
  388. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  389. if (count > 1) {
  390. throw new MultiplePagesHitsError(currentPathname);
  391. }
  392. }
  393. const pageWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  394. const { data: page, meta } = pageWithMeta ?? {};
  395. // add user to seen users
  396. if (page != null && user != null) {
  397. await page.seen(user);
  398. }
  399. props.pageWithMeta = null;
  400. // populate & check if the revision is latest
  401. if (page != null) {
  402. page.initLatestRevisionField(revisionId);
  403. props.isLatestRevision = page.isLatestRevision();
  404. const ssrMaxRevisionBodyLength = configManager.getConfig('app:ssrMaxRevisionBodyLength');
  405. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  406. const populatedPage = await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  407. props.pageWithMeta = {
  408. data: populatedPage,
  409. meta,
  410. };
  411. }
  412. }
  413. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  414. const req: CrowiRequest = context.req as CrowiRequest;
  415. const { crowi } = req;
  416. const Page = crowi.model('Page') as PageModel;
  417. const { currentPathname } = props;
  418. const pageId = getPageIdFromPathname(currentPathname);
  419. const isPermalink = _isPermalink(currentPathname);
  420. const page = props.pageWithMeta?.data;
  421. if (props.isIdenticalPathPage) {
  422. props.isNotCreatable = true;
  423. }
  424. else if (page == null) {
  425. props.isNotFound = true;
  426. props.isNotCreatable = !isCreatablePage(currentPathname);
  427. // check the page is forbidden or just does not exist.
  428. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  429. props.isForbidden = count > 0;
  430. }
  431. else {
  432. props.isNotFound = page.isEmpty;
  433. props.isNotCreatable = false;
  434. props.isForbidden = false;
  435. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  436. if (isPermalink && page.isEmpty) {
  437. props.currentPathname = page.path;
  438. }
  439. // /path/to/page ==> /62a88db47fed8b2d94f30000
  440. if (!isPermalink && !page.isEmpty) {
  441. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  442. if (!isToppage) {
  443. props.currentPathname = `/${page._id}`;
  444. }
  445. }
  446. if (!props.skipSSR) {
  447. props.yjsData = await crowi.pageService.getYjsData(page._id.toString());
  448. }
  449. }
  450. }
  451. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  452. // const req: CrowiRequest = context.req as CrowiRequest;
  453. // const { crowi } = req;
  454. // const UserModel = crowi.model('User');
  455. // if (isUserPage(props.currentPagePath)) {
  456. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  457. // if (user != null) {
  458. // props.pageUser = JSON.stringify(user.toObject());
  459. // }
  460. // }
  461. // }
  462. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  463. const req: CrowiRequest = context.req as CrowiRequest;
  464. const { crowi } = req;
  465. const {
  466. configManager, searchService, aclService, fileUploadService,
  467. slackIntegrationService, passportService,
  468. } = crowi;
  469. props.aiEnabled = configManager.getConfig('app:aiEnabled');
  470. props.limitLearnablePageCountPerAssistant = configManager.getConfig('openai:limitLearnablePageCountPerAssistant');
  471. props.isUsersHomepageDeletionEnabled = configManager.getConfig('security:user-homepage-deletion:isEnabled');
  472. props.isSearchServiceConfigured = searchService.isConfigured;
  473. props.isSearchServiceReachable = searchService.isReachable;
  474. props.isSearchScopeChildrenAsDefault = configManager.getConfig('customize:isSearchScopeChildrenAsDefault');
  475. props.elasticsearchMaxBodyLengthToIndex = configManager.getConfig('app:elasticsearchMaxBodyLengthToIndex');
  476. props.isRomUserAllowedToComment = configManager.getConfig('security:isRomUserAllowedToComment');
  477. props.isSlackConfigured = slackIntegrationService.isSlackConfigured;
  478. // props.isMailerSetup = mailService.isMailerSetup;
  479. props.isAclEnabled = aclService.isAclEnabled();
  480. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  481. props.drawioUri = configManager.getConfig('app:drawioUri');
  482. // props.highlightJsStyle = configManager.getConfig('customize:highlightJsStyle');
  483. props.isAllReplyShown = configManager.getConfig('customize:isAllReplyShown');
  484. props.showPageSideAuthors = configManager.getConfig('customize:showPageSideAuthors');
  485. props.isContainerFluid = configManager.getConfig('customize:isContainerFluid');
  486. props.isEnabledStaleNotification = configManager.getConfig('customize:isEnabledStaleNotification');
  487. props.disableLinkSharing = configManager.getConfig('security:disableLinkSharing');
  488. props.isUploadAllFileAllowed = fileUploadService.getFileUploadEnabled();
  489. props.isUploadEnabled = fileUploadService.getIsUploadable();
  490. // TODO: remove growiCloudUri condition when bulk export can be relased for GROWI.cloud (https://redmine.weseek.co.jp/issues/163220)
  491. props.isBulkExportPagesEnabled = configManager.getConfig('app:isBulkExportPagesEnabled') && configManager.getConfig('app:growiCloudUri') == null;
  492. props.isPdfBulkExportEnabled = configManager.getConfig('app:pageBulkExportPdfConverterUri') != null;
  493. props.isLocalAccountRegistrationEnabled = passportService.isLocalStrategySetup
  494. && configManager.getConfig('security:registrationMode') !== RegistrationMode.CLOSED;
  495. props.adminPreferredIndentSize = configManager.getConfig('markdown:adminPreferredIndentSize');
  496. props.isIndentSizeForced = configManager.getConfig('markdown:isIndentSizeForced');
  497. props.isEnabledAttachTitleHeader = configManager.getConfig('customize:isEnabledAttachTitleHeader');
  498. props.sidebarConfig = {
  499. isSidebarCollapsedMode: configManager.getConfig('customize:isSidebarCollapsedMode'),
  500. isSidebarClosedAtDockMode: configManager.getConfig('customize:isSidebarClosedAtDockMode'),
  501. };
  502. props.rendererConfig = {
  503. isEnabledLinebreaks: configManager.getConfig('markdown:isEnabledLinebreaks'),
  504. isEnabledLinebreaksInComments: configManager.getConfig('markdown:isEnabledLinebreaksInComments'),
  505. isEnabledMarp: configManager.getConfig('customize:isEnabledMarp'),
  506. adminPreferredIndentSize: configManager.getConfig('markdown:adminPreferredIndentSize'),
  507. isIndentSizeForced: configManager.getConfig('markdown:isIndentSizeForced'),
  508. drawioUri: configManager.getConfig('app:drawioUri'),
  509. plantumlUri: configManager.getConfig('app:plantumlUri'),
  510. // XSS Options
  511. isEnabledXssPrevention: configManager.getConfig('markdown:rehypeSanitize:isEnabledPrevention'),
  512. sanitizeType: configManager.getConfig('markdown:rehypeSanitize:option'),
  513. customTagWhitelist: configManager.getConfig('markdown:rehypeSanitize:tagNames'),
  514. customAttrWhitelist: configManager.getConfig('markdown:rehypeSanitize:attributes') != null
  515. ? JSON.parse(configManager.getConfig('markdown:rehypeSanitize:attributes'))
  516. : undefined,
  517. highlightJsStyleBorder: configManager.getConfig('customize:highlightJsStyleBorder'),
  518. };
  519. props.ssrMaxRevisionBodyLength = configManager.getConfig('app:ssrMaxRevisionBodyLength');
  520. }
  521. /**
  522. * for Server Side Translations
  523. * @param context
  524. * @param props
  525. * @param namespacesRequired
  526. */
  527. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  528. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  529. props._nextI18Next = nextI18NextConfig._nextI18Next;
  530. }
  531. const getAction = (props: Props): SupportedActionType => {
  532. if (props.isNotCreatable) {
  533. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  534. }
  535. if (props.isForbidden) {
  536. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  537. }
  538. if (props.isNotFound) {
  539. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  540. }
  541. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  542. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  543. }
  544. return SupportedAction.ACTION_PAGE_VIEW;
  545. };
  546. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  547. const req = context.req as CrowiRequest;
  548. const { user } = req;
  549. const result = await getServerSideCommonProps(context);
  550. // check for presence
  551. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  552. if (!('props' in result)) {
  553. throw new Error('invalid getSSP result');
  554. }
  555. const props: Props = result.props as Props;
  556. if (props.redirectDestination != null) {
  557. return {
  558. redirect: {
  559. permanent: false,
  560. destination: props.redirectDestination,
  561. },
  562. };
  563. }
  564. if (user != null) {
  565. props.currentUser = user.toObject();
  566. }
  567. try {
  568. await injectPageData(context, props);
  569. }
  570. catch (err) {
  571. if (err instanceof MultiplePagesHitsError) {
  572. props.isIdenticalPathPage = true;
  573. }
  574. else {
  575. throw err;
  576. }
  577. }
  578. await injectRoutingInformation(context, props);
  579. injectServerConfigurations(context, props);
  580. await injectNextI18NextConfigurations(context, props, ['translation']);
  581. addActivity(context, getAction(props));
  582. return {
  583. props,
  584. };
  585. };
  586. export default Page;